import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:intl/intl.dart';

import '../../models/forum_message.dart';
import 'logic.dart';

class ForumPage extends StatelessWidget {
  ForumPage({Key? key}) : super(key: key);

  final ForumLogic logic = Get.put(ForumLogic());

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('乡村论坛'),
        backgroundColor: Colors.green,
      ),
      body: Column(
        children: [
          Expanded(
            child: _buildMessageList(),
          ),
          _buildInputArea(),
        ],
      ),
    );
  }

  Widget _buildMessageList() {
    return Obx(() {
      if (logic.isLoading.value) {
        return Center(child: CircularProgressIndicator());
      }

      if (logic.messageList.isEmpty) {
        return Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Icon(Icons.forum_outlined, size: 60, color: Colors.grey),
              SizedBox(height: 16),
              Text(
                '暂无消息，快来发表第一条吧！',
                style: TextStyle(
                  fontSize: 16.sp,
                  color: Colors.grey,
                ),
              ),
            ],
          ),
        );
      }

      return EasyRefresh(
        onRefresh: logic.loadMessages,
        child: ListView.builder(
          padding: EdgeInsets.all(16.w),
          itemCount: logic.messageList.length,
          itemBuilder: (context, index) {
            return _buildMessageCard(logic.messageList[index]);
          },
        ),
      );
    });
  }

  Widget _buildMessageCard(ForumMessage message) {
    return Card(
      margin: EdgeInsets.only(bottom: 16.w),
      elevation: 2,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(12.r),
      ),
      child: Padding(
        padding: EdgeInsets.all(16.w),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Row(
                  children: [
                    CircleAvatar(
                      radius: 16.r,
                      backgroundColor: Colors.green[100],
                      child: Icon(
                        Icons.person,
                        size: 20.r,
                        color: Colors.green,
                      ),
                    ),
                    SizedBox(width: 8.w),
                    Text(
                      message.username,
                      style: TextStyle(
                        fontSize: 14.sp,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ],
                ),
                if (logic.canDeleteMessage(message))
                  IconButton(
                    icon: Icon(Icons.delete_outline, color: Colors.red),
                    onPressed: () => _showDeleteConfirmation(message),
                    padding: EdgeInsets.zero,
                    constraints: BoxConstraints(),
                    iconSize: 20.r,
                  ),
              ],
            ),
            SizedBox(height: 12.h),
            Text(
              message.content,
              style: TextStyle(
                fontSize: 16.sp,
              ),
            ),
            SizedBox(height: 12.h),
            Text(
              _formatDateTime(message.publishDate),
              style: TextStyle(
                fontSize: 12.sp,
                color: Colors.grey,
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildInputArea() {
    return Container(
      padding: EdgeInsets.all(16.w),
      decoration: BoxDecoration(
        color: Colors.white,
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.05),
            blurRadius: 10,
            offset: Offset(0, -5),
          ),
        ],
      ),
      child: Row(
        children: [
          Expanded(
            child: TextField(
              controller: logic.messageController,
              decoration: InputDecoration(
                hintText: '发表你的想法...',
                border: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(24.r),
                  borderSide: BorderSide.none,
                ),
                filled: true,
                fillColor: Colors.grey[100],
                contentPadding: EdgeInsets.symmetric(
                  horizontal: 16.w,
                  vertical: 10.h,
                ),
              ),
              maxLines: 1,
            ),
          ),
          SizedBox(width: 12.w),
          Container(
            decoration: BoxDecoration(
              color: Colors.green,
              shape: BoxShape.circle,
            ),
            child: IconButton(
              icon: Icon(Icons.send, color: Colors.white),
              onPressed: logic.addMessage,
            ),
          ),
        ],
      ),
    );
  }

  void _showDeleteConfirmation(ForumMessage message) {
    Get.dialog(
      AlertDialog(
        title: Text('确认删除'),
        content: Text('确定要删除这条消息吗？'),
        actions: [
          TextButton(
            onPressed: () => Get.back(),
            child: Text('取消'),
          ),
          TextButton(
            onPressed: () {
              Get.back();
              logic.deleteMessage(message.id!);
            },
            child: Text('删除', style: TextStyle(color: Colors.red)),
          ),
        ],
      ),
    );
  }

  String _formatDateTime(String dateTimeString) {
    final dateTime = DateTime.parse(dateTimeString);
    final formatter = DateFormat('yyyy-MM-dd HH:mm');
    return formatter.format(dateTime);
  }
}
